<?php
namespace App\Storage;

use EasySwoole\Component\Singleton;
use EasySwoole\RedisPool\Redis;

class OnlineShop {

    use Singleton;
    protected $table = 'online_shop';

    function __construct($shopId)
    {
        $this->table = $this->table . '_' . $shopId;
    }

    /**
     * 设置一条客服信息。key 是$userId，value是用户信息{'shopId':"shopId",'fd':"fd","last_heartbeat":''}
     * @param $userId
     * @param $data
     */
    function add($userId,$data) {
        $redis = Redis::getInstance()->pool('redis')::defer();
        $redis->hSet($this->table,$userId,json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
    }

    /**
     * 获取一条用户信息
     * @param $userId
     * @return mixed
     */
    function get($userId) {
        $redis = Redis::getInstance()->pool('redis')::defer();
        return json_decode($redis->hGet($this->table,$userId),true);
    }

    /**
     * 更新一条用户信息
     * @param $userId
     * @param $data。 $key 是$userId，value是用户信息{'shopId':"shopId",'fd':"fd","last_heartbeat":'','isShop':'isShop'}
     */
    function update($userId, $data) {
        $redis = Redis::getInstance()->pool('redis')::defer();
        if ($redis->hExists($this->table,$userId)) {
            $redis->hSet($this->table,$userId,json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
        }
    }

    /**
     * 删除一条用户信息
     * @param $userId
     */
    function delete($userId) {
        $redis = Redis::getInstance()->pool('redis')::defer();
        $redis->hDel($this->table,$userId);

    }

    /**
     * 心跳检测
     * @param int $ttl
     */
    function heartbeatCheck($ttl = 60) {
        $redis = Redis::getInstance()->pool('redis')::defer();
        foreach ($redis->hGetAll($this->table) as $userId => $item) {
            $item = json_decode($item,true);
            $time = $item['time'];
            if (($time + $ttl) < $time ) {
                $redis->hDel($this->table,$userId);
            }
        }
    }

    /**
     * 返回当前table
     * @return mixed
     */
    public function table() {
        $redis = Redis::getInstance()->pool('redis')::defer();
        return $redis->hGetAll($this->table);
    }

    /**
     * 返回当前用户总数
     * @return mixed
     */
    public function count() {
        $redis = Redis::getInstance()->pool('redis')::defer();
        return $redis->hlen($this->table);
    }

    /**
     * 返回table中所有的keys
     * @return array
     */
    public function allKeys() {
        $redis = Redis::getInstance()->pool('redis')::defer();
        return $redis->hKeys($this->table);
    }
}